package hikari.persistence;

import com.gooddies.wiring.annotations.Wire;
import com.gooddies.wiring.annotations.WiringComponent;
import hikari.objects3d.Basic3dObject;
import hikari.persistence.file.Chunk;
import hikari.persistence.file.FileSection;
import hikari.persistence.persisthandlers.IPersistantObject3dReadHandler;
import hikari.utils.Utils;
import java.io.IOException;
import java.util.List;
import org.swig.jirr.ISceneManager;

/**
 * @author Dmitry
 */
@WiringComponent
public class Object3dCreator {
    private int parentId = -1;
    private int currentId = -1;
    @Wire
    private PersistantHandlersSettings persistantHandlersSettings;
    @Wire
    private Utils utils;
    public Object3dCreator() {
    }

    public int getCurrentId() {
        return currentId;
    }

    public void setCurrentId(int currentId) {
        this.currentId = currentId;
    }

    public int getParentId() {
        return parentId;
    }

    public void setParentId(int parentId) {
        this.parentId = parentId;
    }

    public Basic3dObject create(ISceneManager sceneManager, FileSection section) throws IOException {
        String objectType = section.readString(section.getChunk("ObjT"));
        IPersistantObject3dReadHandler handler = persistantHandlersSettings.getHandler(objectType);
        if (handler == null) {
            utils.logError("Cannot create object of type " + objectType + " because it is not registered in system.");
            return null;
        }

        Basic3dObject object = handler.read(sceneManager, null, section);
        if (object != null) {
            List<Chunk> attribs = section.getAllAtributes();
            for (Chunk attr : attribs) {
                if ("parent".equals(attr.getName())) {
                    setParentId(section.readInt(attr));
                }
                if ("id".equals(attr.getName())) {
                    setCurrentId(section.readInt(attr));
                }
            }

            List<Chunk> sections = section.getAllSections();
            for (Chunk subSection : sections) {
                IPersistantObject3dReadHandler subHandler = persistantHandlersSettings.getHandler(subSection.getName());
                if (subHandler == null) {
                    utils.logError("Handler for object subsection " + subSection.getName() + " is not registered in system. Skipped.");
                    continue;
                }
                object = subHandler.read(sceneManager, object, section.readSection(subSection));
            }
        }
        return object;
    }
}